package com.my.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.LateCome;
import com.my.entity.NightSpot;
import com.my.entity.UserMonitor;
import com.my.service.LateComeService;
import com.my.service.NightSpotService;
import com.my.service.UserMonitorService;
import com.my.service.UserService;
import com.my.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api")
@CrossOrigin
public class LateComeApiController {

    @Autowired
    private LateComeService service;

    @Autowired
    private UserMonitorService monitorService;

    @Autowired
    private NightSpotService nsService;

    @Autowired
    private UserService uService;

    @PostMapping("lateCome/add")
    public Rest add(@RequestBody LateCome lateCome) {
        if(service.save(lateCome)) {
            return Rest.ok("提交成功！");
        }
        return Rest.err("提交失败！");
    }

    @GetMapping("lateCome")
    public Rest lateCome(Long userId, Long classId) {
        if(userId != null) {
            UserMonitor monitor = monitorService.getOne(new QueryWrapper<UserMonitor>().eq("user_id", userId).eq("type", 2));
            if(monitor != null) {
                userId = null;
                classId = monitor.getGradeClassId();
            }
        }
        Integer userType = null;
        if(userId != null) {
            userType = uService.getById(userId).getType();
        }
        return Rest.ok().setData("list", service.getList(userId, userType, classId));
    }

    @PutMapping("lateComeStatus")
    public Rest lateComeStatus(Long id, Integer status, Long approvalId) {
        LateCome lateCome = service.getById(id);
        if(service.updateById(lateCome.setStatus(status).setApprovalId(approvalId))) {
            if(status == 2) {
                nsService.save(new NightSpot().setStatus(2).setConfirm(true).setUserId(lateCome.getUserId()).setRemarks("晚归申请").setCreateTime(lateCome.getDateTime()));
            }
            return Rest.ok("审核成功！");
        }
        return Rest.err("审核失败！");
    }
    
}
